import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 请求头携带token
    const token = store.getters.token
    if (token) config.headers['x-token'] = token
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  async response => {
    const { data, errmsg, errno } = response.data
    if (errno === 0) {
      // 业务正确
      return data
    } else {
      // 业务错误
      Message.error(errmsg)
      // 区分，如果是token过期，就需要清除token和用户资料，跳转到登录页
      if (errno === 9997) {
        // 触发用户模块下的退出的action
        await store.dispatch('user/logout')
        // 跳转到登录页面(携带当前页面的地址)
        const url = router.history?.current?.path
        router.push(`/login?redirect=${url}`)
      }
      return Promise.reject(errmsg)
    }
  },
  error => {
    // ===========> 请求错误
    return Promise.reject(error)
  }
)

export default service
